<!DOCTYPE html>
  <html dir='rtl'>
  <head>
      <meta charset="utf-8">
      <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
      <title>title</title>
      <link rel="stylesheet" type="text/css" href="../css/api.css"/>
      <link rel="stylesheet" type="text/css" href="../css/map.css"/>
      <link rel="stylesheet" type="text/css" href="../css/mui.picker.min.css"/>
      <style>
			* {
				-webkit-touch-callout: none;
				-webkit-user-select: none;
        -webkit-box-sizing: border-box;
			}
      .mui-dtpicker-header:after {
        clear: both;
        content: '';
        display: block;
        height: 0;
        width: 0;
      }
    	.mui-dtpicker-title h5 {
    	  font-weight: 400;
        color: #8f8f94;
        font-size: 14px;
    	}
      .mui-row {
        display: inline-block;
        position: relative;
      }
      .playsBack {
        position: absolute;
        top: 45px;
        right: 9px;
        width: 30%;
      }
      .mui-btn {
        float: left;
      }
      </style>
  </head>
  <body>
    <div id="main">
    <div id="map"></div>
    <div id="footer">
      <div class="foot">
        <div class="mui-content" id="muiContent">
          <div class="mui-row">
            <div class="mui-col-xs-7">
              <label style="margin-right:9%;" class="text">From</label>
              <input id="fromTime" style="float: left; width: 70%;" readonly value="" data-options='{"type":"datetime"}' class="mui-input-clear">
           </div>
          <div class="mui-col-xs-7">
            <label style="margin-right:18%;" class="text">To</label>
            <input id="toTime" style="float: left; width: 70%;" readonly value="" data-options='{"type":"datetime"}' class="mui-input-clear">
          </div>
          <div class="playsBack">
            <button type="button" id="plays" class="mui-btn">playBack</button>
          </div>
            <!-- <button type="button" id="plays" class="mui-btn">playBack</button> -->
        </div>
      </div>
    </div>
  </div>
  </div>
  </body>
  <script type="text/javascript" src="../script/api.js"></script>
  <script type="text/javascript" src="../script/mui.min.js"></script>
  <script type="text/javascript" src="../script/mui.picker.min.js"></script>
  <script type="text/javascript" src="../script/times.js"></script>
  <script type="text/javascript" src="../script/gps.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDF8b23KBR4I5abL25PcVB930nkq2XeMAs&language=ar&region=EG"></script>
    <script type="text/javascript">
      apiready = function() {
        let plays = $api.byId('plays');
        let userid = api.pageParam.id;
        var iterator = 0;
        var poly = null;
        var ponits = [];
        var position =[];
        var markers = [], infowindows = [];
        var mapData = [];
        var lastIndex=-1;
        var map;
        var maps = null;
        var set;
        //小车图标
        var icon1 = '../image/baibi.png';
        //轨迹点图标
        var carStart = '../image/qidian.png';
        var carEnd = '../image/zhongdian.png';
        var chestop = '../image/chestop.png';
        var overstop = '../image/oversp.png';
        var zb = '../image/zb.png';
        var zn = '../image/zn.png';
        var zd = '../image/zd.png';
        var zx = '../image/zx.png';
        var dn = '../image/dn.png';
        var db = '../image/db.png';
        var xn = '../image/xn.png';
        var xb = '../image/xb.png';
        // console.log(userid)
        let startTime = '';
        let endTime = '';
        let istrue = false;
        let isflag = true;
        plays.addEventListener('click', function() {
          if (!isflag) {
            alert('当前未播放完毕')
            return false;
          }
          if (istrue) {
            for (var i = 0; i < markers.length; i++) {
              markers[i].setMap(null);
            }
            poly.setMap(null);
            mapData = [];
            ponits = [];
            // clearInterval(set);
            iterator = 0;
          }
          startTime = $api.byId('fromTime').value;
          endTime = $api.byId('toTime').value;
          start = startTime.replace(/-/g, "/");
          end = endTime.replace(/-/g, "/");
          let starts = new Date(start);
          let ends = new Date(end);
          var startTimes = startTime.match(/\S+/);
          var endTimes = endTime.match(/\S+/);
          let times = 1000 * 60 * 60 * 24;
          if (startTimes[0] != endTimes[0]) {
            api.toast({
               msg: 'The start month should equals the end time month',
               duration: 3000,
               location: 'middle'
             });
            return false;
          }
          if (starts > ends) {
            api.toast({
               msg: 'The end time is less than the start time',
               duration: 3000,
               location: 'middle'
             });
            return false;
          }
          // if ((ends - starts) / times >= 1 && (ends - starts) / times < 31) {
          //   api.toast({
          //      msg: 'Sorry, you cant cross the day',
          //      duration: 3000,
          //      location: 'middle'
          //    });
          //   return false;
          // }
          // if ((ends - starts) / times > 31) {
          //   api.toast({
          //      msg: 'Sorry, you cant cross the moon',
          //      duration: 3000,
          //      location: 'middle'
          //    });
          //   return false;
          // }
          // if ((ends - starts) / times < 1 && (ends - starts) / times > 0) {
            getData(userid, startTime, endTime);
          // }
        });
        initMap();
        // getData(userid)
        function getData (id, startTime, endTime) {
          console.log(id)
          api.ajax({
            url: 'http://223.255.10.50:8029/dsp-ShateApp-ui/Vehiclemonitor/app/findTrailInfo.action',
            type: 'get',
            data: {
              values: {
                carId: id,  // id
                startDate: startTime,   //  开始时间
                endDate: endTime   //  开始时间
              }
            },
            }, function(ret, err) {
              if (ret) {
                // console.log(JSON.stringify(ret))
                if (ret.data.length === 0) {
                  api.toast({
                    msg: 'There is no data to replay in this period of time',
                    duration: 3000,
                    location: 'middle'
                  });
                 return false;
                }
                initMap(ret.data);
              } else {
                // console.log(JSON.stringify(err));
                api.alert('Server exception');

              }
          });
        }
        function initMap(data) {
          maps = $api.getStorage('maps');
          let wgs = wgs84togcj02(maps.Y, maps.X);
          let gcj = gcj02tobd09(wgs[0], wgs[1]);
          let bd0 = bd09togcj02(gcj[0], gcj[1]);
          map = new google.maps.Map(document.getElementById('map'), {
            zoom: Number(maps.zoom),
            center: new google.maps.LatLng(bd0[0], bd0[1])
          });
          // console.log(data)
          if (typeof data === undefined) return false;
          for (var key in data) {
            mapData = data;
            if (data.length === 0) return false;
              let wgs = wgs84togcj02(data[key].Y, data[key].X);
              let gcj = gcj02tobd09(wgs[0], wgs[1]);
              let bd0 = bd09togcj02(gcj[0], gcj[1]);
              let position = new google.maps.LatLng(parseFloat(bd0[0]), parseFloat(bd0[1]));
              ponits = ponits.concat(position);
              // line.setMap(map);
            // }, 200)
            }
          var polyOptions = {
                strokeColor : 'blue',
                strokeOpacity : 1.0,
                strokeWeight : 1
            };
            poly = new google.maps.Polyline(polyOptions);
            poly.setMap(map);
            // console.log(position.length)
            // console.log(markers.length)
            drop();
            // addMessage();
            // info();
        }
          function drop() {
              for (var i = 0; i < ponits.length; i++) {
                  set = setTimeout(function() {
                      addMarker();
                      // addMessage();
                  }, i * 2000);
              }
            }
            function addMarker() {
              var path = poly.getPath();
              path.push(ponits[iterator]);
              // if (iterator == 0) {
              //   markers.push(new google.maps.Marker({
              //       position : ponits[iterator],
              //       map : map,
              //       icon : icon1
              //   }));
              //   markers[0].setIcon(carStart);
              // }
              if (iterator > 0) {
                if (mapData[0]) {
                  markers[0].setIcon(carStart);
                }
                // if (mapData[iterator] === mapData.length) {
                //   markers[iterator].setIcon(carEnd);
                // }
                if (mapData[iterator].Direction === 'North East') {
                  markers[iterator - 1].setIcon(db);
                }
                if (mapData[iterator].Direction === 'Due East') {
                  markers[iterator - 1].setIcon(zd);
                }
                if (mapData[iterator].Direction === 'Due North') {
                  markers[iterator - 1].setIcon(zb);
                }
                if (mapData[iterator].Direction === 'West') {
                  markers[iterator - 1].setIcon(zx);
                }
                if (mapData[iterator].Direction === 'Due South') {
                  markers[iterator - 1].setIcon(zn);
                }
                if (mapData[iterator].Direction === 'South West') {
                  markers[iterator - 1].setIcon(xn);
                }
                if (mapData[iterator].Direction === 'North West') {
                  markers[iterator - 1].setIcon(xb);
                }
                if (mapData[iterator].Direction === 'South East') {
                  markers[iterator - 1].setIcon(dn);
                }
                // if(mapData[iterator].AbnormalFuelQuantity === 'Yes'){
                //   // console.log()
                //   markers[iterator - 1].setIcon(chestop);
                // }
                if(mapData[iterator].OverspeedingTime === 'Yes'){
                  markers[iterator - 1].setIcon(overstop);
                }
                if(mapData[iterator].TimeoutParkingTimes === 'Yes'){
                  markers[iterator - 1].setIcon(chestop);
                }
              }
              markers.push(new google.maps.Marker({
                  position : ponits[iterator],
                  map : map,
                  icon : icon1
              }));
              map.panTo(ponits[iterator]);
              map.setCenter(markers[iterator].getPosition())
              map.setZoom(Number(maps.zoom))
              addMessage(markers[iterator])
              iterator++;
              isflag = false;
              if (iterator === mapData.length) {
                isflag = true;
                istrue = true;
              }
              // addMessage(markers[iterator])
          }
          function addMessage (markers) {
            var contentString = '<div id="content">'+
              '<div id="siteNotice">PlateNumber：'+mapData[iterator].PlateNumber +'</div>'+
              '<div id="siteNotice">Last On Line Time：'+mapData[iterator].Reporttime +'</div>'+
              '<div id="siteNotice">Speed：'+mapData[iterator].Speed +'</div>'+
              '<div id="siteNotice">Direction：'+mapData[iterator].Direction +'</div>'+
              '<div id="siteNotice">Oil consumption abnormality：'+mapData[iterator].AbnormalFuelQuantity +'</div>'+
              '<div id="siteNotice">Speeding：'+mapData[iterator].OverspeedingTime +'</div>'+
              '<div id="siteNotice">Timeout Parking：'+mapData[iterator].TimeoutParkingTimes +'</div>'+
              '<div id="siteNotice">Parking：'+mapData[iterator].NormalParking +'</div>'+
              '</div>';
            var infowindow = new google.maps.InfoWindow({
                content : contentString
            });
            infowindows.push(infowindow);
            markers.addListener('click', function(e) {
              if (lastIndex!=-1){
                infowindows[lastIndex].close();
              }
              infowindow.open(markers.get('map'), markers);
              lastIndex = infowindows.indexOf(infowindow,0);
            });
        }
    };
</script>
  </html>
